<template>
    <main-layout :showHome="!isFromList" :showBack="isFromList" :title="`${isEdit ? '编辑':'新增'}项目`">
        <div class="form-box">
            <van-form @submit="onSubmit">
                <div class="title">基本信息</div>
                <van-field
                    v-model="pageData.name"
                    label="项目名"
                    placeholder="请输入项目名称"
                    :rules="[{ required: true, message: '请输入项目名称' }]"/>
                <van-field
                    v-model="pageData.signTime"
                    label="签订日期"
                    placeholder="请输入签订日期"
                    :rules="[{ required: true, message: '请输入签订日期' }]">
                    <template #button>
                        <van-button size="small" type="primary" color="#ff5b02" @click="timeShow = true" native-type="button">选择日期</van-button>
                    </template>
                </van-field>
                <van-field
                    v-model="cityName"
                    label="地市"
                    placeholder="请选择地区"
                    :rules="[{ required: true, message: '请选择地区' }]">
                    <template #button>
                        <van-button size="small" type="primary" color="#ff5b02" @click="areaShow = true" native-type="button">选择地区</van-button>
                    </template>
                </van-field>
                <van-field
                    v-model="pageData.address"
                    label="详细地址"
                    placeholder="请输入详细地址"
                    :rules="[{ required: true, message: '请输入详细地址' }]"/>
                <van-field
                    v-model="pageData.liableName"
                    label="负责人"
                    placeholder="请选择负责人"
                    :rules="[{ required: true, message: '请选择负责人' }]">
                    <template #button>
                        <van-button size="small" type="primary" color="#ff5b02" @click="pickPerson()" native-type="button">选择负责人</van-button>
                    </template>
                </van-field>

                <div class="title">业主信息</div>
                <van-field
                    v-model="pageData.ownerName"
                    label="业主"
                    placeholder="请输入业主"
                    :rules="[{ required: true, message: '请输入业主' }]"/>
                <van-field
                    v-model="pageData.ownerAddress"
                    label="业主地址"
                    placeholder="请输入业主地址"
                    :rules="[{ required: true, message: '请输入业主地址' }]"/>
                <van-field
                    v-model="pageData.ownerPhone"
                    label="联系电话"
                    placeholder="请输入联系电话"
                    :rules="[
                        { required: true, message: '请输入联系电话' },
                        { validator, message: '请正确输入联系电话' }
                    ]"/>

                <div class="title">备注信息</div>
                <van-field
                    v-model="pageData.remark"
                    rows="2"
                    autosize
                    label="备注"
                    type="textarea"
                    maxlength="50"
                    placeholder="请输入备注"
                    show-word-limit/>

                <div style="margin: 16px;">
                    <van-button round block type="info" native-type="submit" color="#ff5b02">提交</van-button>
                </div>
            </van-form>
            <!-- 日期组件 -->
            <van-popup v-model="timeShow"
                position="bottom"
                :style="{ height: '308px' }">
                    <van-datetime-picker v-model="signTime"
                        @cancel="timeShow = false"
                        @confirm="pickTime"
                        type="datetime"
                        title="选择年月日"/>
            </van-popup>
            <!-- 地区组件 -->
            <van-popup v-model="areaShow"
                position="bottom"
                :style="{ height: '308px' }">
                <van-area title="选择地市"
                    @cancel="areaShow = false"
                    @confirm="pickArea"
                    :area-list="areaList" />
            </van-popup>
            <!-- 选择负责人 -->
            <van-popup v-model="personShow"
                position="right"
                :style="{ height: '100%', width: '80%' }">
                <div class="user-box">
                    <header>
                        <input type="text" v-model="personQuery.name" placeholder="输入查询关键字">
                        <button @click="pickPerson(true)">查询</button>
                    </header>
                    <ul @scroll="scrollEvt">
                        <li v-for="item in personList"
                            @click="pickUser(item)"
                            :key="item.id">
                            {{item.name}} {{item.dept}} {{item.duties}}
                        </li>
                        <li class="more">
                            {{
                                loading ? '加载中...' : hasMore ? '上滑加载更多' : '不要滑了，没有了'
                            }}
                        </li>
                    </ul>
                </div>
            </van-popup>
        </div>
    </main-layout>
</template>

<script>
import { dateFormat } from '../../util'
import { areaList } from '@vant/area-data'
import { personListApi, projectSaveApi } from '../../apis/projectApi'
export default {
  data () {
    return {
      isFromList: false,
      isEdit: false,
      pageData: {
        name: '',
        liableId: '',
        liableName: '',
        signTime: '',
        province: '',
        city: '',
        county: '',
        address: '',
        ownerId: '',
        ownerName: '',
        ownerAddress: '',
        ownerPhone: '',
        remark: ''
      },
      cityName: '',
      timeShow: false,
      signTime: new Date(),
      areaShow: false,
      areaList,
      personShow: false,
      personList: [],
      // 查询用户信息的查询对象
      personQuery: {
        name: '',
        page: 1,
        size: 20
      },
      loading: false,
      hasMore: true
    }
  },
  created () {
    this.isFromList = !!this.$route.query.from

    this.isEdit = !!this.$route.query.id
  },
  methods: {
    async onSubmit () {
      console.log('-----------onSubmit')
      const citys = this.cityName.split('/')
      this.pageData.province = citys[0]
      this.pageData.city = citys[1]
      this.pageData.county = citys[2]

      const result = await projectSaveApi(this.pageData)

      if (result.code === 200) {
        this.$toast.success('保存成功')
      } else {
        this.$toast.fail('保存失败')
      }
    },
    // 函数校检电话号码
    validator (val) {
      return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(val)
    },
    // 选择时间
    pickTime (val) {
      this.pageData.signTime = dateFormat(val, 'yyyy-MM-dd hh:mm')
      this.timeShow = false
    },
    // 选择地市的确认回调
    pickArea (arr) {
      console.log(arr)
      this.cityName = arr.reduce(function (res, item) {
        res.push(item.name)
        return res
      }, []).join('/')
      this.areaShow = false
    },
    // 打开选择负责人的弹出框
    pickPerson (isQuery) {
      // 需要把查询条件重置为空
      this.personQuery.page = 1
      this.personList = []
      // 加载状态开启
      this.loading = true

      // 发起数据请求
      this.getPersonList()
      // 在执行查询的时候不能调用
      if (!isQuery) {
        this.personQuery.name = ''
        this.personShow = true
      }
    },
    // 获取负责人数据列表
    async getPersonList () {
      const result = await personListApi(this.personQuery)
      if (result.code === 200) {
        this.personList = this.personList.concat(result.data.rows)
        // 判断后端是否还有数据: 当前页面 * 每一页数据个数 一定要小于 总数据
        this.hasMore = this.personQuery.page * this.personQuery.size < result.data.total
      }

      // 因为vue是虚拟dom，而虚拟dom更新和赋值是异步，所以在关闭加载状态时，需要延迟
      setTimeout(() => {
        this.loading = false
      })
    },
    // 滚动加载更多
    scrollEvt () {
      const target = window.event.target

      // 计算是否已经滚动到底部：容器展示高度 + 已经滚动上去的距离 === 容器的真实高度
      const isBottom = (target.clientHeight + target.scrollTop + 20) > target.scrollHeight
      // console.log(this.loading)
      // 因为要做请求节流(第一次请求没有结束的情况下，不能发起第二次请求)，
      // 必须有更多数据，一定要滚动到底部的时候才能执行加载
      if (!this.loading && this.hasMore && isBottom) {
        //   开启节流阀门
        this.loading = true
        this.personQuery.page += 1
        this.getPersonList()
      }
    },
    // 选择具体的负责人
    pickUser (user) {
      this.pageData.liableId = user.id
      this.pageData.liableName = user.name

      this.personShow = false
    }
  }
}
</script>

<style lang="less" scoped>
@import '../../style/common.less';
    .form-box{
        padding: 4px 12px;
        .title{
            display: block;
            font-size: .8rem;
            padding: 10px 0;
        }
    }
    .user-box {
        display: block;
        height: 100%;
        > header {
            display: flex;
            padding: 8px 12px;
            border-bottom: 1px solid @cdd;
            input {
                flex: 1;
                padding: 0;
                outline: none;
                border: none;
                font-size: .7rem;
                color: @c33;
                line-height: 32px;
            }
            button {
                flex: 0 0 68px;
                height: 32px;
                background-color: @primary;
                border: none;
                color: @cff;
                font-size: .7rem;
            }
        }
        ul {
            display: block;
            padding: 8px 12px;
            height: calc(100% - 49px);
            overflow-x: hidden;
            li {
                border-bottom: 1px solid #ddd;
                font-size: .7rem;
                padding: 10px;
                &:last-child {
                    border-bottom: none;
                    color: @c99;
                }
            }
        }
    }
</style>
